import re

from rest_framework import serializers

# 因为有模型，所以用ModelSerializer
from users.models import User, Address

# 前端需要把　username, password, password2,sms_code ,mobile, allow这六个参数传递到后端接口
from users.utils import generic_verify_url


class RegisterCreateUserSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(label="确认密码", write_only=True)
    sms_code = serializers.CharField(label="短信验证码", max_length=6, min_length=6, allow_null=False, write_only=True)
    allow = serializers.CharField(label="是否同意协议", write_only=True, allow_null=False, allow_blank=False)
    token = serializers.CharField(label="token", read_only=True)

    class Meta:
        model = User
        fields = ("id", "username", "password", "mobile", "password2", "sms_code", "allow", 'token')
        extra_kwargs = {
            'id': {'read_only': True},
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    """
    字段的校验方式
    １　字段类型校验
    ２　字段选项校验
    ３　单个字段校验
    ４　多个字段校验
    手机号单个字段校验   密码个确认密码多个字段校验
    短信验证码多个字段校验 allow 单个字段校验
    username这儿不做校验，因为之前已经做过校验

    """

    # 单个字段校验
    def validate_mobile(self, value):
        if not re.match('1[345789]\d{9}', value):
            raise serializers.ValidationError("手机号格式错误！")
        return value

    def validate_allow(self, value):
        if value != "true":
            raise serializers.ValidationError("您为同意协议")
        return value

    # 多个字段校验
    def validate(self, attrs):
        password = attrs.get("password")
        password2 = attrs.get("password2")
        if password != password2:
            raise serializers.ValidationError("密码不一致")

        sms_code = attrs.get("sms_code")
        mobile = attrs.get("mobile")
        from django_redis import get_redis_connection
        redis_conn = get_redis_connection("code")
        redis_sms_code = redis_conn.get("sms_%s" % mobile)
        if redis_sms_code is None:
            raise serializers.ValidationError("验证码已过期")
        # redis 中存放的都是二进制数据
        if sms_code != redis_sms_code.decode():
            raise serializers.ValidationError("验证码不正确")

        return attrs

    def create(self, validated_data):

        del validated_data["password2"]
        del validated_data["sms_code"]
        del validated_data["allow"]

        user = User.objects.create(**validated_data)
        # 密码加密
        user.set_password(validated_data["password"])

        from rest_framework_jwt.settings import api_settings
        # 获取这俩个方法
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER

        # payload获取ｕｓｅｒ的信息，并编码生成ｔｏｋｅｎ
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        user.token = token
        user.save()
        return user


"""
用户中心序列化器
"""


class UserConterInfoSerializer(serializers.ModelSerializer):
    """
       用户详细信息序列化器
       """

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


class EmailSerializer(serializers.ModelSerializer):
    """
    邮箱序列化器
    """

    class Meta:
        model = User
        "只需要转化的用户的ｉｄ，和　email"
        fields = ('email',)

    # 由于使用的是三级视图，所以需要重写ｕｐｄａｔｅ方法
    def update(self, instance, validated_data):
        # 保存邮箱地址
        email = validated_data['email']
        instance.email = validated_data['email']
        instance.save()

        # celery发送邮件
        from celery_tasks.email.tasks import send_verify_email
        send_verify_email.delay(email,instance.id)

        return instance


class AddressSerializer(serializers.ModelSerializer):

    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')


    def create(self, validated_data):
        #Address模型类中有user属性,将user对象添加到模型类的创建参数中
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)